import {
  Body,
  Controller,
  Delete,
  FileTypeValidator,
  Get,
  MaxFileSizeValidator,
  Param,
  ParseFilePipe,
  Post,
  Query,
  UploadedFile,
} from '@nestjs/common';
import { TrackService } from './track.service';
import { Track } from 'src/database/entities/track';
import { TrackListModel } from './dto';
import { Like } from 'typeorm';
import { RedisService } from 'src/database/redis';
import axios from "axios"
import { UploadService } from '../upload/upload.service';
import { error } from 'console';
const FormData = require('form-data')
@Controller('track')
export class TrackController {
  constructor(
    private redisService: RedisService,
    private trackService: TrackService,
    private uploadServers: UploadService
  ) { }

  @Get('list')
  async index(@Query() query: TrackListModel) {
    const where: any = {};
    if (query.name) {
      where.name = Like(`%${query.name}%`); // 使用模糊匹配
    }
    if (query.createdAt) {
    }
    const [results, totalCount] = await Track.findAndCount({
      skip: (query.pageIndex - 1) * query.pageSize,
      take: query.pageSize,
      where,
    });
    return {
      data: results,
      totalCount: totalCount,
      pageSize: query.pageSize,
      pageIndex: query.pageIndex,
    };
  }

  @Get('detail/:id')
  async detail(@Param('id') id: number) {
    return {
      code: 200,
      data: await Track.findOneBy({ id }),
    };
  }

  @Post('edit')
  async update(@Body() track: Track) {
    await Track.save(track);
    return {
      code: 200,
    };
  }

  @Delete('delete/:id')
  async delete(@Param('id') id: number) {
    //delete oss image
    //delete oss model
    //notify 识别
    await Track.delete(id);
    return {
      code: 200,
    };
  }

  @Post('crate')
  async create(@Body() track: Track) {
    const regex = /\.com(\/.+)/; // 捕获 .com 后的所有内容
    const matched = track.fileUrl.match(regex);
    let bufferBody = await this.uploadServers.getObject(matched[1])
    let buffer = Buffer.from(bufferBody.Body)
    const form = new FormData()
    form.append('image', buffer, {
      filename: track.name,       // 文件名，必须指定
      contentType: 'image/png'     // 内容类型，根据你的数据选择
    });
    let results = await axios.post(`http://122.51.165.14/search/InsertImage?lable=${track.name}`,
      form,
      {
        headers: {
          ...form.getHeaders()
        },
      }
    )
    return results
    
  }

  @Post('identify')
  async identify(@UploadedFile(
    new ParseFilePipe({
      validators: [
        new FileTypeValidator({
          fileType: 'image/*',
        }),
        new MaxFileSizeValidator({ maxSize: 1024 * 1024 * 5 }),
      ],
    }),
  )
  file: Express.Multer.File,) {
    let formdata = new FormData()
    formdata.append('image', file.buffer.toString('binary'))
    await axios.post('122.51.165.14/search/CheckImage',
      formdata
    )

    await this.redisService.redis.incr('identify');

  }

  @Get('getDayIdentify')
  async todayIdentify() {
    return {
      data: await this.redisService.redis.get('identify'),
    };
  }
}
